﻿namespace Microsoft.SharePoint.Client
{
    using System;
    using System.Collections.Generic;
    using System.Linq.Expressions;
    using System.Reflection;

    internal static class ExpressionUtility
    {
        private static Type FindIEnumerable(Type seqType)
        {
            if ((seqType != null) && (seqType != typeof(string)))
            {
                if (seqType.IsArray)
                {
                    return typeof(IEnumerable<>).MakeGenericType(new Type[] { seqType.GetElementType() });
                }
                if (seqType.IsGenericType)
                {
                    foreach (Type type in seqType.GetGenericArguments())
                    {
                        Type type2 = typeof(IEnumerable<>).MakeGenericType(new Type[] { type });
                        if (type2.IsAssignableFrom(seqType))
                        {
                            return type2;
                        }
                    }
                }
                Type[] interfaces = seqType.GetInterfaces();
                if ((interfaces != null) && (interfaces.Length > 0))
                {
                    foreach (Type type3 in interfaces)
                    {
                        Type type4 = FindIEnumerable(type3);
                        if (type4 != null)
                        {
                            return type4;
                        }
                    }
                }
                if ((seqType.BaseType != null) && (seqType.BaseType != typeof(object)))
                {
                    return FindIEnumerable(seqType.BaseType);
                }
            }
            return null;
        }

        internal static Type GetElementType(Type seqType)
        {
            Type type = FindIEnumerable(seqType);
            if (type == null)
            {
                return seqType;
            }
            return type.GetGenericArguments()[0];
        }

        public static bool IsGetFieldValueMethod(MethodInfo method)
        {
            PseudoRemoteAttribute customAttribute = (PseudoRemoteAttribute) Attribute.GetCustomAttribute(method, typeof(PseudoRemoteAttribute));
            return ((customAttribute != null) && (customAttribute.Name == "GetFieldValue"));
        }

        public static Expression StripConverts(Expression exp)
        {
            while ((exp != null) && (exp.NodeType == ExpressionType.Convert))
            {
                exp = ((UnaryExpression) exp).Operand;
            }
            return exp;
        }

        public static Expression StripQuotes(Expression exp)
        {
            while ((exp != null) && (exp.NodeType == ExpressionType.Quote))
            {
                exp = ((UnaryExpression) exp).Operand;
            }
            return exp;
        }
    }
}

